import http.server
import socketserver
import os
import socket

# 搭建http服务，从而可以通过网络访问指定目录下的图片
def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except Exception as e:
        print(f"发生错误: {e}")
        return None


# 配置图片所在的路径
IMAGE_DIR = "f:/data/image"

# 切换到图片目录
os.chdir(IMAGE_DIR)

# 定义服务器端口
PORT = 8000

# 创建一个 HTTP 服务器
Handler = http.server.SimpleHTTPRequestHandler

local_ip = get_local_ip()
if local_ip:
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"服务器正在运行，可通过 http://{local_ip}:{PORT} 访问图片目录 {IMAGE_DIR}")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("服务器已停止")
else:
    print("无法获取本地 IP 地址，无法启动服务器。")
